package training.bms.presentation;

import java.util.Iterator;

import javax.faces.FacesException;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExceptionHandler;
import javax.faces.context.ExceptionHandlerWrapper;
import javax.faces.context.FacesContext;
import javax.faces.event.ExceptionQueuedEvent;
import javax.faces.event.ExceptionQueuedEventContext;

import training.bms.business.BusinessException;

public class ExceptionHandlerImpl extends ExceptionHandlerWrapper {

	private ExceptionHandler defaultHandler;

	public ExceptionHandlerImpl(ExceptionHandler defaultHandler){
		this.defaultHandler = defaultHandler;
	}

	@Override
	public ExceptionHandler getWrapped() {

		return defaultHandler;
	}

	@Override
	public void handle() throws FacesException {
		Iterable<ExceptionQueuedEvent> events = getUnhandledExceptionQueuedEvents();
		events.iterator();

		for (Iterator<ExceptionQueuedEvent> i = events.iterator() ; i.hasNext();){
			ExceptionQueuedEvent event = i.next();
			ExceptionQueuedEventContext context = event.getContext();
			Throwable exception = context.getException();
			BusinessException businessException = findBusinessException(exception);
			if(businessException!= null){
				FacesMessage message = new FacesMessage();


				message.setSummary(businessException.getMessage());
				message.setSeverity(FacesMessage.SEVERITY_ERROR);

				FacesContext faceContext = FacesContext.getCurrentInstance();
				faceContext.addMessage(null, message);
				i.remove();
			}else{
				//PlaceHolder
			}

		}
		super.handle();
	}

	private BusinessException findBusinessException(Throwable exception) {
		while(exception != null){
			if (exception instanceof BusinessException){
				return (BusinessException) exception;
			}else{
				exception = exception.getCause();
			}
		}
		return null;
	}

}
